package com.kirichof.matchreminder.persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.kirichof.matchreminder.core.Log;
import com.kirichof.matchreminder.model.TeamMate;

public class PersistenceManager {

	/** Connexió a la base de dades */
	private static Connection connection = null;

	public static List<TeamMate> getTeamMateList() throws SQLException,
			ClassNotFoundException {
		List<TeamMate> companys = new ArrayList<TeamMate>();

		Statement selectJugadors = getConnection().createStatement();
		selectJugadors.setQueryTimeout(30);
		ResultSet rs = selectJugadors
				.executeQuery("SELECT * FROM jugadors_equip");

		while (rs.next()) {
			TeamMate company = new TeamMate(rs.getInt("id"),
					rs.getString("nom"), rs.getString("email"));
			companys.add(company);
		}
		return companys;
	}

	public static Connection getConnection() throws ClassNotFoundException,
			SQLException {
		if (connection == null || connection.isClosed()) {
			// load the sqlite-JDBC driver using the current class loader
			Class.forName("org.sqlite.JDBC");
			connection = DriverManager
					.getConnection("jdbc:sqlite:/opt/300/workspace/MatchReminder/src/com/kirichof/matchreminder/persistence/300.db");
		}
		return connection;
	}

	private static void checkConnection() throws SQLException,
			ClassNotFoundException {
		if (connection.isClosed()) {
			Log.info("Connection got closed. Creating new connection.");
			getConnection();
		}
	}

}
